package com.serverapk.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;

public class SocketUtil {

//	private static final String TAG = "SocketUtil";
//	private static final String HOST = "192.168.9.83";
//	private static final int PORT = 60322;
	private Socket socket = null;
	private SocketAddress saddress = null;

	private InputStream in = null;
	private OutputStream out = null;
	
	String host = "";
	int port = 0;

	private boolean start_flag = true;
	
	public SocketUtil(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void sockStart() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					saddress = new InetSocketAddress(host, port);
					socket = new Socket();
					socket.connect(saddress, 30000);
					in = socket.getInputStream();
					out = socket.getOutputStream();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public boolean waitForConnect() {
		boolean ret = false;
		int count = 0;

		if (isConnect()) {
			return true;
		}

		if (start_flag) {
			sockStart();
			while (count < 3) {
				if (isConnect()) {
					ret = true;
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				count++;
			}
			start_flag = false;
		}
		return ret;
	}

	public boolean isConnect() {
		boolean isConnect = false;
		if (socket != null && socket.isConnected()) {
			isConnect = true;
		}
		return isConnect;
	}

	public void setSoTimeout(int val) {
		try {
			if (socket != null)
				socket.setSoTimeout(val);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public void sockStop() {
		try {
			if (in != null) {
				in.close();
				in = null;
			}

			if (out != null) {
				out.close();
				out = null;
			}

			if (socket != null) {
				socket.close();
				socket = null;
			}
		} catch (IOException e) {
		}
		start_flag = true;
	}

	public void writeSockData(byte[] msg) {
		if (isConnect() && out != null) {
			try {
				out.write(msg);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public int readSockData(byte[] msg) {
		int len = 0;
		if (isConnect() && in != null) {
			try {
				len = in.read(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return len;
	}

}
